package com.bloom.product.qms.mda.service;

import com.bloom.cloud.common.service.BaseService;
import com.bloom.cloud.core.dao.PageResult;
import com.bloom.cloud.core.db.DS;
import com.bloom.cloud.core.model.web.TableQueryCriteria;
import com.bloom.cloud.core.utils.DateUtils;
import com.bloom.cloud.core.utils.SQLUtil;
import com.bloom.product.qms.mda.entity.*;
import com.bloom.product.qms.mda.vo.MdaFastReversalDataVo;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.lang.reflect.Field;
import java.util.*;
import java.util.stream.Collectors;

@Service("tbQualityProblemService")
public class TbQualityProblemService extends BaseService<TbQualityProblem> {

    @Autowired
    private TbInterimMeasureService tbInterimMeasureService;
    @Autowired
    private TbLongTermMeasureService tbLongTermMeasureService;
    @Autowired
    private TbProblemProcessService tbProblemProcessService;
    @Autowired
    private TbReasonAnalyseService tbReasonAnalyseService;
    @Autowired
    private ActRuHistoryService ActRuHistoryService;
    @Autowired
    private TbQualityProblemService tbQualityProblemService;

    private static final String TYPE_G = "G";
    private static final String TYPE_Y = "Y";
    private static final String TYPE_R = "R";
    private static final String TYPE_NA = "N/A";

    public List<Map<String,Object>> getUnCloseHierarchicalAudit() {
        Map<String, Object> params = new HashMap();
        return super.getSqlSession().selectList("TbQualityProblemMapper.getUnCloseHierarchicalAudit");
    }

    @DS(value = "qms")
    public PageResult<TbQualityProblem> getHierarchicalAuditListByCriteria(TableQueryCriteria criteria){
        criteria.setQueryPage(true);
        criteria.setUseCacheSql(false);
        criteria.setQueryRelationEntity(false);
        criteria.addQueryCondition("ifHidden","N");
//        criteria.addQueryCondition("problemStatusIN","DRAFT,RELEASE");
//        criteria.addQueryCondition("qualityProblemType","HIERARCHICAL_AUDIT_PROBLEM");
        return super.findBy(criteria);
    }

    @DS(value = "qms")
    public PageResult<TbQualityProblem> getFastReversalListByCriteria(TableQueryCriteria criteria){
        criteria.setQueryPage(true);
        criteria.setUseCacheSql(false);
        criteria.setQueryRelationEntity(false);
        criteria.addQueryCondition("ifHidden","N");
        return super.findBy(criteria);
    }

    public PageResult<MdaFastReversalDataVo> fastReversal(TableQueryCriteria criteria) {
        //分页查询问题数据
        PageResult<TbQualityProblem> pageResult = tbQualityProblemService.getFastReversalListByCriteria(criteria);
        List<TbQualityProblem> problemDataList = pageResult.getContent();
        PageResult<MdaFastReversalDataVo> pageResultRtn = new PageResult<>();
        pageResultRtn.setCurrentPage(pageResult.getCurrentPage());
        pageResultRtn.setPageSize(pageResult.getPageSize());
        pageResultRtn.setTotalPage(pageResult.getTotalPage());
        pageResultRtn.setTotalCount(pageResult.getTotalCount());
        pageResultRtn.setCurrentIndex(pageResult.getCurrentIndex());


        List<TbQualityProblem> problemList = new ArrayList<>();
        for(int i=0;i<problemDataList.size();i++){
            problemList.add(SQLUtil.changeMapToBean(TbQualityProblem.class,(Map<String,Object>)problemDataList.get(i)));
        }

        //返回给MDA的数据集合
        List<MdaFastReversalDataVo> rtnList = new ArrayList<>();
        if(problemList != null && problemList.size() > 0){
            Set<Integer> processIdList = problemList.stream().map(TbQualityProblem::getProblemProcessId).collect(Collectors.toSet());
            Set<String> instanceIdList = problemList.stream().map(TbQualityProblem::getProcessInstanceId).collect(Collectors.toSet());
            String processIds,instanceIds;
            boolean hasProcessAll = false;
            if(processIdList != null && processIdList.size() > 0){
                processIds = processIdList.toString().replace("[", "").replace("]", "");
                instanceIds = instanceIdList.toString().replace("[", "").replace("]", "");
                hasProcessAll = true;
            }else{
                hasProcessAll = false;
                processIds = "-1";
                instanceIds = "-1";
            }
            Map<Integer, List<TbInterimMeasure>> interimMeasureMap = new HashMap<>();
            Map<Integer, List<TbLongTermMeasure>> longTermMeasureMap = new HashMap<>();
            Map<Integer, List<TbProblemProcess>> problemProcessMap = new HashMap<>();
            Map<Integer, List<TbReasonAnalyse>> reasonAnalyseMap = new HashMap<>();
            Map<String, List<ActRuHistory>> actRuHistoryMap = new HashMap<>();
            if(hasProcessAll){
                //短期措施
                List<TbInterimMeasure> interimMeasureDataList = tbInterimMeasureService.getListByProcessIds(processIds);
                List<TbInterimMeasure> interimMeasureList = new ArrayList<>();
                for(int i=0;i<interimMeasureDataList.size();i++){
                    interimMeasureList.add(SQLUtil.changeMapToBean(TbInterimMeasure.class,(Map<String,Object>)interimMeasureDataList.get(i)));
                }
                interimMeasureMap = interimMeasureList.stream().collect(Collectors.groupingBy(TbInterimMeasure::getProblemProcessId));
                //长期措施
                List<TbLongTermMeasure> longTermMeasureDataList = tbLongTermMeasureService.getListByProcessIds(processIds);
                List<TbLongTermMeasure> longTermMeasureList = new ArrayList<>();
                for(int i=0;i<longTermMeasureDataList.size();i++){
                    longTermMeasureList.add(SQLUtil.changeMapToBean(TbLongTermMeasure.class,(Map<String,Object>)longTermMeasureDataList.get(i)));
                }
                longTermMeasureMap = longTermMeasureList.stream().collect(Collectors.groupingBy(TbLongTermMeasure::getProblemProcessId));
                //问题关联流程信息
                List<TbProblemProcess> problemProcessDataList = tbProblemProcessService.getListByProcessIds(processIds);
                List<TbProblemProcess> problemProcessList = new ArrayList<>();
                for(int i=0;i<problemProcessDataList.size();i++){
                    problemProcessList.add(SQLUtil.changeMapToBean(TbProblemProcess.class,(Map<String,Object>)problemProcessDataList.get(i)));
                }
                problemProcessMap = problemProcessList.stream().collect(Collectors.groupingBy(TbProblemProcess::getId));
                //原因分析
                List<TbReasonAnalyse> reasonAnalyseDataList = tbReasonAnalyseService.getListByProcessIds(processIds);
                List<TbReasonAnalyse> reasonAnalyseList = new ArrayList<>();
                for(int i=0;i<reasonAnalyseDataList.size();i++){
                    reasonAnalyseList.add(SQLUtil.changeMapToBean(TbReasonAnalyse.class,(Map<String,Object>)reasonAnalyseDataList.get(i)));
                }
                reasonAnalyseMap = reasonAnalyseList.stream().collect(Collectors.groupingBy(TbReasonAnalyse::getProblemProcessId));
                //审批历史
                List<ActRuHistory> actRuHistoryDataList = ActRuHistoryService.getListByInstanceIds(instanceIds);
                List<ActRuHistory> actRuHistoryList = new ArrayList<>();
                for(int i=0;i<actRuHistoryDataList.size();i++){
                    actRuHistoryList.add(SQLUtil.changeMapToBean(ActRuHistory.class,(Map<String,Object>)actRuHistoryDataList.get(i)));
                }
                actRuHistoryMap = actRuHistoryList.stream().collect(Collectors.groupingBy(ActRuHistory::getProcInstId_));
            }

            Date now = new Date();
            for(TbQualityProblem qualityProblem : problemList){
                MdaFastReversalDataVo vo = new MdaFastReversalDataVo();
                BeanUtils.copyProperties(qualityProblem,vo);
                String emergencyMeasureNode = TYPE_Y,rootCauseNode=TYPE_Y,longTermMeasureNode=TYPE_Y,errorProofNode=TYPE_Y,hierarchicalAuditNode=TYPE_Y,longTermMeasureVerifyNode=TYPE_Y,fileNode="",pfmeaNode=TYPE_Y,operationInstructionNode=TYPE_Y,lessonsLearnNode=TYPE_Y,currentStatusNode=TYPE_Y;
                Date processCreateTime = new Date();
                if(qualityProblem.getProblemProcessId() != null){
                    //临时措施
                    List<TbInterimMeasure> interimMeasureList = interimMeasureMap.get(qualityProblem.getProblemProcessId());
                    String measureInterim = "",planDateInterim="",actualDateInterim="";
                    if(interimMeasureList != null && interimMeasureList.size() > 0){
                        for(TbInterimMeasure interimMeasure : interimMeasureList){
                            measureInterim += (interimMeasure.getReasonCountermeasure()+";");
                            if(interimMeasure.getPlanDateInterim() != null){
                                planDateInterim += (DateUtils.formatDate(interimMeasure.getPlanDateInterim(),DateUtils.FORMAT_DATE_DEFAULT)+";");
                            }
                            if(interimMeasure.getActualDateInterim() != null){
                                actualDateInterim += (DateUtils.formatDate(interimMeasure.getActualDateInterim(),DateUtils.FORMAT_DATE_DEFAULT)+";");
                            }
                        }
                        if(measureInterim.contains(";")){
                            measureInterim = measureInterim.substring(0,measureInterim.lastIndexOf(";"));
                        }
                        if(planDateInterim.contains(";")){
                            planDateInterim = planDateInterim.substring(0,planDateInterim.lastIndexOf(";"));
                        }
                        if(actualDateInterim.contains(";")){
                            actualDateInterim = actualDateInterim.substring(0,actualDateInterim.lastIndexOf(";"));
                        }
                    }
                    vo.setMeasureInterim(measureInterim);
                    vo.setPlanDateInterim(planDateInterim);
                    vo.setActualDateInterim(actualDateInterim);
                    //根本原因
                    String rootCauseFiveWhy = "";
                    List<TbReasonAnalyse> reasonAnalyseList = reasonAnalyseMap.get(qualityProblem.getProblemProcessId());
                    if(reasonAnalyseList != null && reasonAnalyseList.size() > 0){
                        for(TbReasonAnalyse reasonAnalyse : reasonAnalyseList){
                            rootCauseFiveWhy += (reasonAnalyse.getReasonAnalyse()+";");
                        }
                        if(rootCauseFiveWhy.contains(";")){
                            rootCauseFiveWhy = rootCauseFiveWhy.substring(0,rootCauseFiveWhy.lastIndexOf(";"));
                        }
                    }

                    String problemDesc = "";//问题描述
                    String rootCause = "";//根本原因
                    String pfmeaRequire = "",operationInstructionRequire="";

                    List<TbProblemProcess> problemProcessList = problemProcessMap.get(qualityProblem.getProblemProcessId());
                    if(problemProcessList != null && problemProcessList.size() > 0){
                        TbProblemProcess problemProcess = problemProcessList.get(0);
                        processCreateTime = problemProcess.getCreateTime();
                        pfmeaRequire = problemProcess.getPfmeaRequire();
                        operationInstructionRequire = problemProcess.getOperationInstructionRequire();
                        if("FAST_REVERSAL_FLOW".equals(problemProcess.getProcessType())){
                            problemDesc = "[制造]"+getStr(problemProcess.getMakeDescription())+";[流出]"+getStr(problemProcess.getEscapePointDescription());
                            rootCause = "[制造]"+getStr(problemProcess.getMakeRootCause())+";[流出]"+getStr(problemProcess.getEscapePointRootCause());
                        }else{
                            problemDesc = "[流出]"+getStr(problemProcess.getEscapePointDescription());
                            rootCause = "[制造]"+getStr(rootCauseFiveWhy) + ";[流出]"+getStr(problemProcess.getEscapePointRootCause());
                        }
                    }
                    vo.setRootCause(rootCause);
                    vo.setProblemDesc(problemDesc);
                    //长期措施
                    String errorProof="",hierarchicalAudit="";
                    List<TbLongTermMeasure> longTermMeasureList = longTermMeasureMap.get(qualityProblem.getProblemProcessId());
                    String measureLongTerm = "",planDateLongTerm="",actualDateLongTerm="";
                    if(longTermMeasureList != null && longTermMeasureList.size() > 0){
                        for(TbLongTermMeasure longTermMeasure : longTermMeasureList){
                            //只要有一条数据是需要分层审核或者防错检验的   那么这条数据就需要
                            if(!TYPE_Y.equals(errorProof)){
                                errorProof = longTermMeasure.getErrorProof();
                            }
                            if(!TYPE_Y.equals(hierarchicalAudit)){
                                hierarchicalAudit = longTermMeasure.getHierarchicalAudit();
                            }

                            measureLongTerm += (longTermMeasure.getMeasure()+";");
                            if(longTermMeasure.getPlanDate() != null){
                                planDateLongTerm += (DateUtils.formatDate(longTermMeasure.getPlanDate(),DateUtils.FORMAT_DATE_DEFAULT)+";");
                            }
                            if (longTermMeasure.getActualDate() != null){
                                actualDateLongTerm += (DateUtils.formatDate(longTermMeasure.getActualDate(),DateUtils.FORMAT_DATE_DEFAULT)+";");
                            }
                        }
                        if(measureLongTerm.contains(";")){
                            measureLongTerm = measureLongTerm.substring(0,measureLongTerm.lastIndexOf(";"));
                        }
                        if(planDateLongTerm.contains(";")){
                            planDateLongTerm = planDateLongTerm.substring(0,planDateLongTerm.lastIndexOf(";"));
                        }
                        if(actualDateLongTerm.contains(";")){
                            actualDateLongTerm = actualDateLongTerm.substring(0,actualDateLongTerm.lastIndexOf(";"));
                        }
                    }
                    vo.setMeasureLongTerm(measureLongTerm);
                    vo.setPlanDateLongTerm(planDateLongTerm);
                    vo.setActualDateLongTerm(actualDateLongTerm);
                    Long hour =(now.getTime() - processCreateTime.getTime())/1000/60/60;
                    //审批历史
                    List<ActRuHistory> actRuHistoryList = actRuHistoryMap.get(qualityProblem.getProcessInstanceId());

                    if(actRuHistoryList != null && actRuHistoryList.size() > 0){
                        for(ActRuHistory actRuHistory : actRuHistoryList){
                            //遏制措施节点
                            if(actRuHistory.getApproveNode().indexOf("D0") > -1){
                                if("SUBMIT".equals(actRuHistory.getApproveResult()) || "PASS".equals(actRuHistory.getApproveResult())){
                                    emergencyMeasureNode = TYPE_G;
                                }else if(!TYPE_G.equals(emergencyMeasureNode)){
                                    if(hour > 24L){
                                        emergencyMeasureNode = TYPE_R;
                                    }else{
                                        emergencyMeasureNode = TYPE_Y;
                                    }
                                }
                            }
                            //根本原因
                            else if(actRuHistory.getApproveNode().indexOf("D4") > -1){
                                if("SUBMIT".equals(actRuHistory.getApproveResult()) || "PASS".equals(actRuHistory.getApproveResult())){
                                    rootCauseNode = TYPE_G;
                                }else if(!TYPE_G.equals(rootCauseNode)){
                                    if(hour > 7*24L){
                                        rootCauseNode = TYPE_R;
                                    }else{
                                        rootCauseNode = TYPE_Y;
                                    }
                                }
                            }
                            //长措制定
                            else if(actRuHistory.getApproveNode().indexOf("D5") > -1){
                                if("SUBMIT".equals(actRuHistory.getApproveResult()) || "PASS".equals(actRuHistory.getApproveResult())){
                                    longTermMeasureNode = TYPE_G;
                                    errorProofNode = TYPE_G;
                                    hierarchicalAuditNode = TYPE_G;
                                }else if(!TYPE_G.equals(longTermMeasureNode)){
                                    if(hour > 14*24L){
                                        longTermMeasureNode = TYPE_R;
                                        errorProofNode = TYPE_R;
                                        hierarchicalAuditNode = TYPE_R;
                                    }else{
                                        longTermMeasureNode = TYPE_Y;
                                        errorProofNode = TYPE_Y;
                                        hierarchicalAuditNode = TYPE_Y;
                                    }
                                }
                            }
                            //长措验证
                            else if(actRuHistory.getApproveNode().indexOf("D6") > -1){
                                if("SUBMIT".equals(actRuHistory.getApproveResult()) || "PASS".equals(actRuHistory.getApproveResult())){
                                    longTermMeasureVerifyNode = TYPE_G;
                                }else if(!TYPE_G.equals(longTermMeasureVerifyNode)){
                                    if(hour > 28*24L){
                                        longTermMeasureVerifyNode = TYPE_R;
                                    }else{
                                        longTermMeasureVerifyNode = TYPE_Y;
                                    }
                                }
                            }
                            //文件固化
                            else if(actRuHistory.getApproveNode().indexOf("D7") > -1){
                                if("SUBMIT".equals(actRuHistory.getApproveResult()) || "PASS".equals(actRuHistory.getApproveResult())){
                                    //fileNode节点只做判断使用
                                    fileNode = TYPE_G;
                                    pfmeaNode = TYPE_G;
                                    operationInstructionNode = TYPE_G;
                                }else if(!TYPE_G.equals(fileNode)){
                                    if(hour > 29*24L){
                                        fileNode = TYPE_R;
                                        pfmeaNode = TYPE_R;
                                        operationInstructionNode = TYPE_R;
                                    }else{
                                        fileNode = TYPE_Y;
                                        pfmeaNode = TYPE_Y;
                                        operationInstructionNode = TYPE_Y;
                                    }
                                }
                            }
                        }
                    }

                    if("N".equals(errorProof)){
                        errorProofNode = TYPE_NA;
                    }
                    if("N".equals(hierarchicalAudit)){
                        hierarchicalAuditNode = TYPE_NA;
                    }
                    if("N".equals(pfmeaRequire)){
                        pfmeaNode = TYPE_NA;
                    }
                    if("N".equals(operationInstructionRequire)){
                        operationInstructionNode = TYPE_NA;
                    }
                }

                //判断经验教训的状态（根据审批过程中填写的是否需要自动生成LESSON&LEARN来判断）
                if(StringUtils.isNotBlank(qualityProblem.getAutoLessonsLearn())){
                    if("Y".equals(qualityProblem.getAutoLessonsLearn())){
                        lessonsLearnNode = TYPE_G;
                    }else{
                        lessonsLearnNode = TYPE_NA;
                    }
                }else{
                    if(qualityProblem.getProblemProcessId() == null || StringUtils.isBlank(String.valueOf(qualityProblem.getProblemProcessId()))){
                        lessonsLearnNode = TYPE_Y;
                    }else{
                        Long hour =(now.getTime() - processCreateTime.getTime())/1000/60/60;
                        if(hour > 31*24L){
                            lessonsLearnNode = TYPE_R;
                        }else{
                            lessonsLearnNode = TYPE_Y;
                        }
                    }
                }

                vo.setEmergencyMeasureNode(emergencyMeasureNode);
                vo.setErrorProofNode(errorProofNode);
                vo.setHierarchicalAuditNode(hierarchicalAuditNode);
                vo.setLongTermMeasureNode(longTermMeasureNode);
                vo.setLongTermMeasureVerifyNode(longTermMeasureVerifyNode);
                vo.setLessonsLearnNode(lessonsLearnNode);
                vo.setRootCauseNode(rootCauseNode);
                vo.setOperationInstructionNode(operationInstructionNode);
                vo.setPfmeaNode(pfmeaNode);
                //当前状态如何判断
                if("4/4".equals(qualityProblem.getCurrentProgress())){
                    vo.setCurrentStatusNode(TYPE_G);
                }else{
                    vo.setCurrentStatusNode(currentStatusNode);
                }
                vo.setChargePersonNameDept(getStr(qualityProblem.getChargePersonName())+"-"+getStr(qualityProblem.getChargePersonDept()));
                vo.setProblemId(qualityProblem.getId());
                rtnList.add(vo);
            }
        }
        pageResultRtn.setContent(rtnList);
        return pageResultRtn;
    }

    private String getStr(Object o){
        String s = String.valueOf(o);
        if(o != null && StringUtils.isNotBlank(s) && !"null".equals(s)){
            return s;
        }else{
            return"";
        }
    }

}
